package com.seuic.scannerapitest.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import com.seuic.mdm.IDeviceManagement;
import com.seuic.misc.Misc;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;
import com.seuic.scanner.StatusCallBack;
import com.seuic.scannerapitest.activity.DeviceModel.DeviceType;
import com.seuic.touch.TouchService;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;

/**
 * 厂家实现这个类
 * @author zhaojian10
 *
 */
public class InnerScannerImpl implements InnerScannerI,DecodeInfoCallBack,StatusCallBack{
	Scanner scanner;
	OnScanListener onScanListener;
	boolean isScanning = false;//是否正在扫描
	private IDeviceManagement mDeviceManagement;
	
	private Context mContext = null;
	
	private final static String TOPATH = Environment.getExternalStorageDirectory()+"/ZIP/";
	
	public InnerScannerImpl(Context context) {
		mContext = context;
		scanner = ScannerFactory.getScanner(mContext);
		scanner.open();
		scanner.setDecodeInfoCallBack(this);
		scanner.setStatusCallBack(this);
		scanner.setParams(0x07, 3);
		isScanning = false;
		
		// 创建所需绑定的Service的Intent
		Intent intent = new Intent();
		intent.setAction("com.seuic.mdm.MdmService");
		// 绑定远程MdmService
		mContext.bindService(intent, conn, Service.BIND_AUTO_CREATE);
	}
	
	/**
	 * 启动扫码
	 * @param timeout
	 */
	public synchronized void start(int timeout){
		if(scanner==null){
			scanner = ScannerFactory.getScanner(mContext);
			scanner.open();
			scanner.setDecodeInfoCallBack(this);
			scanner.setStatusCallBack(this);
			scanner.setParams(0x07, 3);
			isScanning = false;
			
			// 创建所需绑定的Service的Intent
			Intent intent = new Intent();
			intent.setAction("com.seuic.mdm.MdmService");
			// 绑定远程MdmService
			mContext.bindService(intent, conn, Service.BIND_AUTO_CREATE);
		}
		
		if(isScanning){
			return;
		}
		isScanning = true;
		
		new MyThread(timeout).start();
		
		scanner.startScan();
	}
	
	class MyThread extends Thread{
		int timeout;
		
		public MyThread(int timeout){
			this.timeout = timeout;
		}
		
		@Override
		public void run() {
			int count = timeout/1000;
			if(count>0){
				for(int i=0;i<count;i++){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(!isScanning){
						return;
					}
				}
			}else{
				try {
					Thread.sleep(timeout);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//自己超时关闭
			InnerScannerImpl.this.stop();
			
			super.run();
		}
	}
	
	/**
	 * 停止扫码，关闭扫描红外线
	 */
	public synchronized void stop(){
		scanner.stopScan();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		isScanning = false;
	}
	
	public void setOnScanListener(OnScanListener onScanListener){
		this.onScanListener = onScanListener;
	}

	public void stopListen(){
		if(!isScanning){
			this.onScanListener = null;
		}
		
	}
	
	@Override
	public void close() {
		mContext.unbindService(conn);
		scanner.stopScan();
		scanner.close();
		scanner.setStatusCallBack(null);
		scanner.setDecodeInfoCallBack(null);
		scanner = null;
	}

	@Override
	public void onDecodeComplete(final DecodeInfo arg0) {
		 new Handler(Looper.getMainLooper()).post(new Runnable() {
             @Override
             public void run() {
            	 if(onScanListener!=null){
            		 onScanListener.onScanSuccess(arg0.barcode);
            	 }
            	
            	 isScanning = false;
             }
         });
		 
	}

	@Override
	public void onStatusCallBack(int arg0, int arg1) {
		isScanning = false;
	}

	private ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// 获取远程Service的onBind方法返回的对象的代理
			mDeviceManagement = IDeviceManagement.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mDeviceManagement = null;
		}
	};
	
	@Override
	public boolean silentInstall(String zipPath) {
	    File zipFile = new File(zipPath);
		try {
			upZipFile(zipFile, TOPATH);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		List<File> filelist = getFileList(TOPATH);
		if(filelist!=null&&filelist.size()>0){
			for(File item:filelist){
				try {
					mDeviceManagement.silentInstall(item.getAbsolutePath());
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
				item.delete();
			}
			
			return true;
		}
		
		return false;
	}
	
	//遍历解压文件夹的apk文件
	 public static ArrayList<File> getFileList(String strPath) {
		    ArrayList<File> filelist = new ArrayList<File>();
		    File dir = new File(strPath);
		    File[] files = dir.listFiles();
		    if (files == null)
		      return null;
		    for (int i = 0; i < files.length; i++) {
		        if(files[i].getName().toLowerCase().endsWith("apk"))
		          filelist.add(files[i]);
		    }
		    return filelist;
		  }

	/**
	 * 解压缩一个文件
	 * 
	 * @param zipFile
	 *            要解压的压缩文件
	 * @param folderPath
	 *            解压缩的目标目录
	 * @throws IOException
	 *             当解压缩过程出错时抛出
	 */
	public void upZipFile(File zipFile, String folderPath) throws ZipException,
			IOException {
		File desDir = new File(folderPath);
		if (!desDir.exists()) {
			desDir.mkdirs();
		}

		ZipFile zf = new ZipFile(zipFile);
		for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
			ZipEntry entry = ((ZipEntry) entries.nextElement());
			InputStream in = zf.getInputStream(entry);
			String str = folderPath + File.separator + entry.getName();
			str = new String(str.getBytes("8859_1"), "GB2312");
			File desFile = new File(str);
			if (!desFile.exists()) {
				File fileParentDir = desFile.getParentFile();
				if (!fileParentDir.exists()) {
					fileParentDir.mkdirs();
				}
				desFile.createNewFile();
			}
			OutputStream out = new FileOutputStream(desFile);
			byte buffer[] = new byte[1024];
			int realLength;
			while ((realLength = in.read(buffer)) > 0) {
				out.write(buffer, 0, realLength);
			}
			in.close();
			out.close();
		}
	}

	@Override
	public boolean setVirKeyDisabled(int disableMask) {
		return TouchService.getInstance().setVirKeyDisabled(disableMask);
	}

	@Override
	public int getVirKeyDisabled() {
		return TouchService.getInstance().getVirKeyDisabled();
	}

	@Override
	public int getStatusBarEnabled() {
		Misc misc = new  Misc();
		return misc.getStatusBarEnabled(mContext);
	}

	@Override
	public void setStatusBarEnabled(int enable) {
		Misc misc = new  Misc();
		misc.setStatusBarEnabled(mContext,enable);
	}

	@Override
	public void setHomeDisable() {
		TouchService.getInstance().setVirKeyDisabled(TouchService.VKEY2_DISABLE_MASK);
	}

	@Override
	public void setBackDisable() {
		DeviceType mDeviceType = DeviceModel.getDeviceType();
		if(DeviceType.device_d500p==mDeviceType){
			TouchService.getInstance().setVirKeyDisabled(TouchService.VKEY3_DISABLE_MASK);
		}else if(mDeviceType==DeviceType.device_d700||mDeviceType==DeviceType.device_d700c){
			TouchService.getInstance().setVirKeyDisabled(TouchService.VKEY1_DISABLE_MASK);
		}
	}

	@Override
	public void setMenuDisable() {
		DeviceType mDeviceType = DeviceModel.getDeviceType();
		if(DeviceType.device_d500p==mDeviceType){
			TouchService.getInstance().setVirKeyDisabled(TouchService.VKEY1_DISABLE_MASK);
		}else if(mDeviceType==DeviceType.device_d700||mDeviceType==DeviceType.device_d700c){
			TouchService.getInstance().setVirKeyDisabled(TouchService.VKEY3_DISABLE_MASK);
		}
	}

}
